//
//  SightPicViewerVC.m
//  Sight
//
//  Created by lanou3g  on 14/11/12.
//  Copyright (c) 2014年lanou3g. All rights reserved.
//

#import "PicViewerVC.h"



@interface PicView : UIView<UIScrollViewDelegate>

// 可扩展背景
@property (nonatomic, strong) UIScrollView *scaleBg;

// 图片
@property (nonatomic, strong) UIImageView *pic;

@end

@implementation PicView




- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        // 图像动作 scrollView
        _scaleBg = [[UIScrollView alloc] initWithFrame:self.bounds];
        [_scaleBg setBackgroundColor:[UIColor blackColor]];
        [_scaleBg setShowsVerticalScrollIndicator:NO];
        [_scaleBg setShowsHorizontalScrollIndicator:NO];
        [_scaleBg setScrollsToTop:NO];
        [_scaleBg setClipsToBounds:NO];
        //减速速率
        [_scaleBg setDecelerationRate:UIScrollViewDecelerationRateFast];
        [_scaleBg setMaximumZoomScale:3.0f];
        [_scaleBg setMinimumZoomScale:1.0f];
        [_scaleBg setDelegate:self];
        [self addSubview:_scaleBg];
        
        
        // 创建imageView
        self.pic = [[UIImageView alloc] initWithFrame:self.bounds];
        //自适应
        self.pic.contentMode = UIViewContentModeScaleAspectFit;
        //不透明
        [_pic setOpaque:YES];
        [_pic setMultipleTouchEnabled:YES];
        [_pic setUserInteractionEnabled:YES];
        [_scaleBg addSubview:_pic];
        
    }
    return self;
}

- (void)loadUrl:(NSString *)imgUrl placeholderImage:(UIImage*)placeholderImage {
    [self.pic sd_setImageWithURL:[NSURL URLWithString:imgUrl] placeholderImage:nil completed:nil];
}

#pragma mark - 事件处理函数
// 取消放大处理
- (void)cancelScale {
    if (![_scaleBg zoomScale] > 1.0f)  {
        return;
    }
    
    [UIView animateWithDuration:0.3 animations:^{
        [_scaleBg setZoomScale:1.0];
        [_scaleBg setContentOffset:CGPointMake(0.0, 0.0) animated:YES];
    }];
    
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return _pic;
}

@end



// 照片间隙
static const CGFloat PADDING = 10;

// 图片起始值
static const NSInteger kImgBaseTag = 100;

// 显示图片张数Label的高度
static const CGFloat kCountLabelHeight  = 30;

@interface PicViewerVC ()

@property (nonatomic, strong) UIScrollView *scroll;

// 当前第几张
@property (nonatomic, strong) UILabel *progress;
@property(nonatomic,strong)UITextView *textView;
@property(nonatomic,strong)UILabel *timeLable;

@end


@implementation PicViewerVC


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [[self view] setBackgroundColor:[UIColor clearColor]];

    // 手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapImageBack:)];
    [self.view addGestureRecognizer:tap];
    
    
    // 创建ScrollView
    _scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(-PADDING, 0, self.view.width + 2*PADDING, self.view.height)];
    [_scroll setBackgroundColor:[UIColor blackColor]];
    [_scroll setShowsVerticalScrollIndicator:NO];
    [_scroll setShowsHorizontalScrollIndicator:NO];
    [_scroll setMultipleTouchEnabled:YES];
    [_scroll setPagingEnabled:YES];
    [_scroll setCanCancelContentTouches:YES];
    [_scroll setDelegate:self];
    [self setupScroll];
    [self.view addSubview:_scroll];
    
//    self.navigationController.navigationBarHidden = YES;

    
    // 提示浮层
    NSInteger defaultIndex = [_arrayLargeImages count] > 0 ? _curImageIndex+1 : 0;
    NSString *countText = [NSString stringWithFormat:@"%ld / %lu",(long)defaultIndex,(unsigned long)[_arrayLargeImages count]];
    _progress = [[UILabel alloc] initWithFrame:CGRectMake(0,kCountLabelHeight, self.view.width, kCountLabelHeight)];
    self.progress.text = countText;
    self.progress.font = [UIFont systemFontOfSize:12];
    self.progress.textColor = [UIColor whiteColor];
    [_progress setBackgroundColor:[UIColor clearColor]];
    [_progress setTextAlignment:NSTextAlignmentCenter];
    [self.view addSubview:_progress];
    
    
    [self refreshImage:_curImageIndex];
}

- (void)tapImageBack:(id)sender {
    
//    self.navigationController.navigationBar.hidden = NO;
//    [self.navigationController popViewControllerAnimated:NO];
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}


-(void)viewDidDisappear:(BOOL)animated{
    
    self.navigationController.navigationBar.hidden = NO;
    
}

// 创建图片内容ScrollView的子界面
- (void)setupScroll
{
    [_scroll removeAllSubviews];
    
    NSUInteger imgCount = [_arrayLargeImages count];
    
    [_scroll setContentSize:CGSizeMake(imgCount * (self.view.width + PADDING * 2), 0)];
    
    for (NSInteger i=0; i<imgCount; i++) {
        
        PicView *picV = [[PicView alloc] initWithFrame:CGRectMake(i * (self.view.width + PADDING*2) + PADDING,
                                                                  0,
                                                                  self.view.width,
                                                                  self.view.height)];
        picV.tag = kImgBaseTag + i;
        
        [_scroll addSubview:picV];
    }
    
    // 判断是否是有效索引
    if (_curImageIndex < imgCount) {
        [_scroll setContentOffset:CGPointMake(_curImageIndex * (self.view.width + PADDING * 2), 0)];
    }
    
}

// 刷新图片
- (void)refreshImage:(NSInteger)index
{
    // 加载图像
    if ((index >= 0) && (index < [_arrayLargeImages count]))
    {
        [self setCurImageIndex:index];
        
        [self loadAndShowImage:index];
        
        if (index - 1 >= 0)
        {
            PicView *picV = (PicView *)[_scroll viewWithTag:kImgBaseTag + index - 1];
            
            if (picV) {
                [picV cancelScale];
            }
        }
        
        if (index < [_arrayLargeImages count] - 1) {
            
            PicView *picV = (PicView *)[_scroll viewWithTag:kImgBaseTag + index + 1];
            
            if (picV) {
                [picV cancelScale];
            }
            
        }
    }
}

// 显示和图片数据
- (void)loadAndShowImage:(NSInteger)index
{
    if (_scroll != nil) {
        PicView *picV = (PicView *)[_scroll viewWithTag:kImgBaseTag + index];
        if (picV) {
            if(index == self.originIndex){
                [picV loadUrl:[_arrayLargeImages objectAtIndex:index] placeholderImage:self.originPlaceholderImage];
            }
            else{
                [picV loadUrl:[_arrayLargeImages objectAtIndex:index] placeholderImage:nil];
            }
        }
    }
}


// =======================================================================
#pragma mark - UIScrollViewDelegate代理函数
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    // 当是main scrollView时触发换页事件
    if (scrollView == _scroll)
    {
        CGFloat pageWidth = scrollView.frame.size.width;
        NSInteger pageIndex = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
        
        if (pageIndex != _curImageIndex)
        {
            //切换图片
            [self refreshImage:pageIndex];
            [self updateProgress];
            
        }
    }
    
}

#pragma mark - 更新进度
- (void)updateProgress
{
    if (_progress) {
        [_progress setText:[NSString stringWithFormat:@"%ld / %lu",(long)(_curImageIndex+1), (unsigned long)[_arrayLargeImages count]]];
        
    }
}

-(void)setArrayLargeImages:(NSArray *)arrayLargeImages
{
    _arrayLargeImages = arrayLargeImages;
    [self loadAndShowImage:_curImageIndex];
}

@end